package com.spps;

import java.io.File;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;

public class Application {
    Config config;

    JDBCUtils jdbcUtils;

    Application(String[] args) {
        config = new Config(args);

        HashMap<String, String> dataSource = new HashMap<>();

        // 数据库操作
        String url = "jdbc:mysql://localhost:3306/" + config.get("databaseName") + "?useSSL=false";
        jdbcUtils = new JDBCUtils(url, config.get("user"), config.get("password"));

        // 根据行为调用相应处理逻辑
        switch (config.get("action")) {
            case "make:model":
                dataSource = getModelDataSource();
                break;
            case "make:controller":
                dataSource = getControllerDataSource();
                break;
            case "make:api":
                dataSource = getApiDataSource();
                break;
            case "make:view":
                dataSource = getViewDataSource();
                break;
            default:
                System.out.println("The command can not be found.");
                break;
        }

        migrate(config.get("sourcePath"), config.get("outputPath"), dataSource);
    }

    private void migrate(String sourcePath, String outputPath, HashMap<String, String> dataSoure) {
        if (FileSystem.isDirectory(sourcePath)) {
            File[] files;
            try {
                files = FileSystem.listFiles(sourcePath);
                for (File file : files) {
                    String newOutputPath = outputPath + "/"
                            + FileSystem.getFileName(file.toString()).replaceAll(".tpl", "");
                    TemplateParser templateParser = new TemplateParser(FileSystem.getFileContent(file.toString()));
                    templateParser.parseVariable(dataSoure);
                    templateParser.parseEquals(dataSoure);
                    templateParser.parseLoop(getFields());
                    String fileContent = templateParser.compile();
                    FileSystem.saveFileContent(fileContent, newOutputPath);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            TemplateParser templateParser = new TemplateParser(FileSystem.getFileContent(sourcePath));
            templateParser.parseVariable(dataSoure);
            templateParser.parseEquals(dataSoure);
            templateParser.parseLoop(getFields());
            String fileContent = templateParser.compile();
            FileSystem.saveFileContent(fileContent, outputPath);
        }
    }

    private HashMap<String, String> getViewDataSource() {
        HashMap<String, String> dataSource = new HashMap<>();
        dataSource.put("moduleName", config.get("moduleName"));
        dataSource.put("viewName", config.get("viewName"));
        return dataSource;
    }

    private HashMap<String, String> getApiDataSource() {
        HashMap<String, String> dataSource = new HashMap<>();
        dataSource.put("moduleName", config.get("moduleName"));
        dataSource.put("apiName", config.get("apiName"));
        return dataSource;
    }

    private HashMap<String, String> getControllerDataSource() {
        HashMap<String, String> dataSource = new HashMap<>();
        dataSource.put("moduleName", config.get("moduleName"));
        dataSource.put("controllerName", config.get("controllerName"));
        dataSource.put("tableName", getTableName().replaceAll(config.get("prefix") + "_", ""));
        return dataSource;
    }

    private HashMap<String, String> getModelDataSource() {
        // 数据源
        HashMap<String, String> dataSource = new HashMap<>();

        String tableName = getTableName();
        try {
            ResultSet resultSet = jdbcUtils.executeQuery("SHOW COLUMNS FROM " +
                    tableName);
            if (resultSet.next()) {
                dataSource.put("primaryKey", resultSet.getString("Field"));
            }
        } catch (Exception e) {
        }

        dataSource.put("moduleName", config.get("moduleName"));
        dataSource.put("modelName", config.get("modelName"));
        dataSource.put("tableName", tableName.replaceAll(config.get("prefix") + "_", ""));

        return dataSource;
    }

    String getTableName() {
        String tableName = "";
        if (!config.get("prefix").isEmpty()) {
            tableName += config.get("prefix") + "_";
        }
        if (config.get("tableName").isEmpty()) {
            if (!config.get("moduleName").isEmpty()) {
                if (!config.get("modelName").isEmpty() && !config.get("moduleName").equals(config.get("modelName"))) {
                    tableName += config.get("moduleName") + "_";
                }
                if (!config.get("controllerName").isEmpty()
                        && !config.get("moduleName").equals(config.get("controllerName"))) {
                    tableName += config.get("moduleName") + "_";
                }
                if (!config.get("apiName").isEmpty() && !config.get("moduleName").equals(config.get("apiName"))) {
                    tableName += config.get("moduleName") + "_";
                }
                if (!config.get("viewName").isEmpty() && !config.get("moduleName").equals(config.get("viewName"))) {
                    tableName += config.get("moduleName") + "_";
                }
            }
            if (!config.get("modelName").isEmpty()) {
                tableName += config.get("modelName");
            }
            if (!config.get("controllerName").isEmpty()) {
                tableName += config.get("controllerName");
            }
            if (!config.get("apiName").isEmpty()) {
                tableName += config.get("apiName");
            }
            if (!config.get("viewName").isEmpty()) {
                tableName += config.get("viewName");
            }
        } else {
            tableName += config.get("tableName");
        }
        tableName = tableName.replace("-", "_");
        return tableName;
    }

    ArrayList<HashMap<String, String>> getFields() {
        // 字段列表
        ArrayList<HashMap<String, String>> fields = new ArrayList<>();

        // 查询数据库
        try {
            ResultSet resultSet = jdbcUtils.executeQuery("SHOW COLUMNS FROM " + getTableName());
            while (resultSet.next()) {
                HashMap<String, String> field = new HashMap<>();
                field.put("name", StringUtils.toLowerCamelCase(resultSet.getString("Field")));
                field.put("type", resultSet.getString("Type"));
                fields.add(field);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return fields;
    }
}
